package cn.hackertools.staticresource.service;

import cn.hackertools.staticresource.dao.ProjectDao;
import cn.hackertools.staticresource.entity.Project;
import cn.hackertools.staticresource.utils.FileHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Date;
import java.util.UUID;

@Service
public class ProjectServiceImpl {
    @Autowired
    private ProjectDao projectDao;
    @Value(value = "${static-resouce-file-path}")
    private String fileRootPath;

    @Autowired
    private FileHandler fileHandler;
    public void createProject(Project project){
        String uuid = UUID.randomUUID().toString();
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:SS");
        project.setCreateTime(simpleDateFormat.format(new Date()));
        project.setId(uuid);
        projectDao.save(project);
        String filePath=fileRootPath+ File.separator+project.getId();
        System.out.println(filePath);
        File dir=new File(filePath);
        if(!dir.exists()||(dir.exists()&&dir.isFile()))
        {
            dir.mkdirs();
        }

    }

    public List<Project> getList(){
        Iterable<Project> all = projectDao.findAll();
        List<Project> datas=new ArrayList<>();
        all.forEach(p->{
            datas.add(p);
        });
        return datas;
    }

    public void delProject(String projectId){
        String dirPath=fileRootPath+File.separator+projectId;
        File dir=new File(dirPath);
        if(dir.exists()&&!dir.isFile())
        {
            fileHandler.deleteDir(dirPath);
        }
        projectDao.deleteById(projectId);
    }


}
